package com.eelye.util.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class ErrorcodeExceptionHandler implements HandlerExceptionResolver {

//    private static final ObjectMapper objectMapper;
//    static {
//        objectMapper = new ObjectMapper();
//        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
//        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//    }

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception pe) {
//        try {
//            //虽然Decripted了，但为了兼容性，还是这样用
//            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//
//            int code = SystemError.getCode();
//            String err = "Unknown";
//            if (pe instanceof CodedException) {
//                CodedException e = (CodedException) pe;
//                code = e.getCode();
//                err = e.getMessage();
//            }
//
//            Map<String, Object> responseContent = new HashMap<>();
//            responseContent.put("data", null);
//            responseContent.put("errcode", code);
//            responseContent.put("errmsg", err);
//            httpServletResponse.getWriter()
//                    .write(objectMapper.writeValueAsString(responseContent));
//            if( code > 50000 ) {
//                httpServletResponse.setStatus(500);
//            }
//            //必须直接输出，要不不起作用.
//            httpServletResponse.getWriter().flush();
//        } catch (IOException ex) {
//            log.error("ErrorcodeExceptionHandler.resolveException error.", ex);
            //既然这个函数没有要求返回值，那就不会出错，要不然框架就会错了。
//        }

        return new ModelAndView();
    }
}
